<?php
namespace app\admin\controller;

use think\Db;
use think\View;
use think\Request;
use think\Session;
class Index extends Common
{
    public function index(){
         $admin_id   = session('admin_id');
         if ($admin_id == '1'){
             $nav = Db::name('auth_rule')->field('id,pid,title,icon,name')->where("ismenu = 1")->order("id asc")->select();
         }else{
             //获取所有权限的菜单栏
             $Auth= new \Auth();
             $admin_rules = $Auth->getGroups($admin_id); 
             $rules = explode(',',$admin_rules[0]['rules']);
             //获取导航栏列表
             $where['id'] = array('in',$rules);
             $where['ismenu'] = 1;
             $nav = Db::name('auth_rule')->field('id,pid,title,icon,name')->where($where)->order("id asc")->select();
         }

         foreach($nav as $key => $value){
             if ($value['pid'] == 0){
                 $data[$key]['title'] = $value;
                 foreach($nav as $key2 => $value2){
                     if ($value2['pid'] == $value['id']){
                         $data[$key]['nav'][$key2] =$value2;
                         $data[$key]['nav'][$key2]['name'] = url($value2['name']);
                     }
                 }
             }
         }

         $this->assign('nav',$data);
        return view();
    }

    public function logout(){
        Session::set('admin_id',null);
        if (!Session::has('admin_id')){
            return ['code'=>0];
        }else{
            return ['code'=>1];
        }
    }

    public function editPassword(){
        if (Request::instance()->isAjax()){
            $post = Request::instance()->post();
            //加密方式
            $hasher = new \PasswordHash(8, false);
            //将密码进行哈希，结果是一个长度为60个字符的字符串
            $saveData['admin_password'] = $hasher->HashPassword($post['data']['admin_password']);
            $saveData['admin_id'] = Session::get('admin_id');
            $res = Db::name('admin')->update($saveData);
            if ($res){
                Session::clear();
                return ['code'=>0];
            }else{
                return ['code'=>1];
            }
        }
    }
}
